package ru.hh.school.commands;

import ru.hh.school.User;
import ru.hh.school.UserManager;
import ru.hh.school.logging.Logger;

import static ru.hh.school.MessagesManager.message;

public class NickCommand extends AbstractCommand {
    private final UserManager manager;

    public NickCommand(Logger logger, UserManager manager) {
        super(logger);
        this.manager = manager;
    }

    public String getCommand() {
        return "/nick";
    }

    public String getDescription() {
        return message("command.nick.description");
    }

    public void process(User user, String newNick) {
        if (!newNick.equals("")) {
            String oldNick = user.getNick();
            if (!manager.tryTakeNick(oldNick, newNick)) {
                user.sendMessage(message("command.nick.notify.user.error.nick.is.already.taken", newNick));
            } else {
                String roomMessage;
                if (oldNick != null) {
                    roomMessage = message("command.nick.notify.room.user.change.name", oldNick, newNick);
                } else {
                    roomMessage = message("command.nick.notify.room.user.joins.room", newNick);
                }
                user.setNick(newNick);
                user.sendMessage(message("command.nick.notify.user.nick.change", newNick));
                user.getRoom().send(roomMessage, user);
            }
        } else {
            user.sendMessage(message("command.nick.notify.user.error.empty.nick.is.not.allowed"));
        }
    }
}